/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import entity.ExCourse;
import entity.LogMessage;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author psed
 */
@Stateless
public class ExCourseSession {

    @PersistenceContext(unitName = "Exchanger")
    private EntityManager em;
    private List values;
    private List<String> currency;
    private LogMessage message;

    public List<ExCourse> retrieve() {
        return em.createNamedQuery("ExCourse.findAll").getResultList();
    }

    public List<LogMessage> messagesRetrieve() {
        Query getAllMessagesQuery = em.createNamedQuery("LogMessage.findAll");
        return getAllMessagesQuery.getResultList();
    }

    public List<BigDecimal> getValues() {
        values = new ArrayList<BigDecimal>();
        List<ExCourse> courses = em.createQuery("Select ec FROM ExCourse ec").getResultList();
        for (ExCourse exCourse : courses) {
            values.add(exCourse.getIndollars());
        }
        return values;
    }

    public List<String> getCurrency() {
        currency = new ArrayList<String>();
        List<ExCourse> courses = em.createQuery("Select ec FROM ExCourse ec").getResultList();
        for (ExCourse exCourse : courses) {
            currency.add(exCourse.getCurrency());
        }
        return currency;
    }

    public float getExchangeRate(String fromCurrency, String toCurrency) {
        List<ExCourse> from = em.createQuery("SELECT exCourse FROM ExCourse exCourse WHERE exCourse.currency = '" + fromCurrency + "'").getResultList();
        List<ExCourse> to = em.createQuery("SELECT exCourse FROM ExCourse exCourse WHERE exCourse.currency = '" + toCurrency + "'").getResultList();
        return to.get(0).getIndollars() / from.get(0).getIndollars();
    }
}
